//
//  YFPostTopicViewController.m
//  PhotoManager
//
//  Created by Coollang on 2017/9/5.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFPostTopicViewController.h"
#import "YFTopicSynShareCell.h"
#import "YFTopicTextviewCell.h"
#import "YFTopicPhotoCell.h"
#import "YFTopicModel.h"
#import "YFMoveCollection.h"
#import "Masonry.h"
#import "PhotoActionSheetViewController.h"
#import "UIView+JCDrawTool.h"
#import <Qiniu/QiniuSDK.h>
#import "JCLocation.h"
#import "JCGetLocation.h"
#import "JCMomentsModel.h"
#import "UIImage+HXExtension.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "YFShareManager.h"
#import "UIColor+Extension.h"
#import "UIImage+Wechat.h"
#import "YYKit/YYKit.h"
#import "YFMomentApi.h"
#import "YFAlertHelper.h"
#import "YFUserDefaults.h"
#import "YFLoginHelper.h"
#import "YFLoginApi.h"

#define kPhotoSpace 6
#define kPhotoLeftMargin 16
#define kPhotoCol 3        // 图片一行的列数

#define kFooterMaxH (kYFScreenHeight - (kAutoHei(120) + kAutoHei(78) + kAutoHei(94) + 64 + 14) + 6);

@interface YFPostTopicViewController ()<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource,YFMoveCollectionDelegate>

@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;
@property (nonatomic, strong) YFMoveCollection *collectionView;

@property (nonatomic, weak) UIView *bottomMaskView;
@property (nonatomic, strong) UIBarButtonItem *sendItem;
@property (nonatomic, strong,readonly) NSArray *dataSourceArr;

@property (nonatomic, strong) NSMutableArray *photoModelList;

@property (nonatomic, strong) YFTopicModel *textModel;
@property (nonatomic, strong) YFTopicModel *shareModel;
@property (nonatomic, strong) YFTopicModel *addModel;

/** 需要同步到的平台 */
@property (nonatomic, assign)SSDKPlatformType  shareType;
/** 发送的文字内容 */
@property (nonatomic, strong) NSString *topicText;
/** 是否公开位置 */
@property (nonatomic, assign)BOOL openLocation;
/** 用户经纬度信息 */
@property (nonatomic, strong) CLLocation *userLocation;
/** 上传到QN后的图片链接 */
@property (nonatomic, strong) NSArray *uploadedImagesArr;

@end

@implementation YFPostTopicViewController {
    // 不得已之举，后期最后将collectionview改成tableview
    // 好不得已啊😏
    CGFloat _bgImageScale;
    UIImageView *_collectionViewBgView;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.openLocation = YES; // 默认公开
    self.view.backgroundColor = kSeparationLineColor;
    [self configuerNav];
    [self configuerMoveCollectionView];
    self.seletePhotoManager.delegate = self;
    // 进来就去获取位置信息
    [self getUserLocation];
}
- (void)getUserLocation {
    
    if (self.type == PostTopicTypeFeedBack) {
        //用户反馈无需定位
        return;
    }
    if ([CLLocationManager locationServicesEnabled] && ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        //定位功能可用
        
    }else if ([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {
        //定位不能用
        return;
    }
    
    if(self.userLocation == nil && self.openLocation){
        __weak typeof(self) weakSelf = self;
        [[JCLocation shareInstance] getCLLocationCallBack:^(CLLocation *location, NSError *error) {
            if (error) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakSelf getUserLocation];
                });
            }else {
                weakSelf.userLocation = location;
            }
        }];
    }else{
        [[JCLocation shareInstance] stopLocation];
    }
}

- (void)configuerNav {
    if (self.type == PostTopicTypeMoment) {
        self.title = @"Publishing dynamics";
    }else {
        self.title = @"User Feedback";
    }
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_cencel"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction:)];
    self.sendItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Feed_postTopic"] style:UIBarButtonItemStylePlain target:self action:@selector(postTopicAction:)];
    self.navigationItem.rightBarButtonItem = self.sendItem;
    [self UpdateSendItemState];
}

- (void)configuerMoveCollectionView {
    
    self.collectionView = [[YFMoveCollection alloc] initWithFrame:CGRectZero collectionViewLayout:self.flowLayout];
    [self.view addSubview:self.collectionView];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    UIView *maskView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 64, kScreenWidth, kScreenHeight)];
    self.bottomMaskView = maskView;
    [self.view addSubview:maskView];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.moveDelegate = self;
    self.collectionView.backgroundColor = kBgThemeColor;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    UIImageView *backImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, kYFScreenHeight)];
    backImg.image = [self changeColectionViewBackgroundImageWithScale:0.45];
    _bgImageScale = 0.45;
    _collectionViewBgView = backImg;
    self.collectionView.backgroundView = backImg;
    
    /*注册Cell*/
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YFTopicPhotoCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([YFTopicPhotoCell class])];
    [self.collectionView registerClass:[YFTopicTextviewCell class] forCellWithReuseIdentifier:NSStringFromClass([YFTopicTextviewCell class])];
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([YFTopicSynShareCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([YFTopicSynShareCell class])];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"MoveCollectFooter"];
}

- (UIImage *)changeColectionViewBackgroundImageWithScale:(CGFloat)scale {
    UIImage *image = [UIView drawBackgroundImageWith:CGRectMake(0, 0, kYFScreenWidth, kYFScreenHeight) gradiendtRect:CGRectMake(0, kYFScreenHeight * (1-scale), kYFScreenWidth, kYFScreenHeight * scale) startColor:kSeparationLineColor endColor:kSeparationLineColor];
    return image;
}

- (void)seletePhotoDidFinishPickingPhotos:(NSArray<UIImage *> *)photos assets:(NSArray *)assets isOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    [self updatePhotoModelList];
    [self UpdateSendItemState];
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
}
- (void)updatePhotoModelList {
    
    if (_photoModelList.count > 0) {
        [_photoModelList removeAllObjects];
    }
    
    for (NSInteger i = 0; i<self.seletePhotoManager.selectedAssets.count; i++) {
        id asset = self.seletePhotoManager.selectedAssets[i];
        YFTopicModel *model = [[YFTopicModel alloc] initWithType:[YFSeletePhotoManager isVideoWithAsset:asset] ? kYFTopicModelMediaTypeVideo:kYFTopicModelMediaTypePhoto];
        model.seleteImage = self.seletePhotoManager.selectedPhotos[i];
        model.asset = asset;
        [self.photoModelList addObject:model];
    }
    
    if (![self.seletePhotoManager isExistVideo] && self.seletePhotoManager.selectedAssets.count < 6) {
        [self.photoModelList addObject:self.addModel];
    }
}

- (void)UpdateSendItemState {
    if (self.seletePhotoManager.selectedAssets.count > 0|| self.topicText.length >= 1) {
        self.sendItem.enabled = YES;
    }else {
        self.sendItem.enabled = NO;
    }
}


#pragma mark - 发布话题相关接口调用逻辑
- (void)postTopicCompleted:(void(^)(BOOL success))completedBlock {
    
    //上传图片到七牛
    [self uploadImagesQNComplated:^(NSArray *imageUrlArr, NSError *error) {
        
        if (error) {
            completedBlock(NO);
            return;
        }
        
        if (_type == PostTopicTypeMoment) {
            //发表帖子
            NSString *userLocationStr = (self.openLocation && self.userLocation) ? [NSString stringWithFormat:@"%f,%f",self.userLocation.coordinate.longitude,self.userLocation.coordinate.latitude]:@"";
            self.openLocation = NO;
            
            YFMomentApi *postTopicApi = [YFMomentApi postTopicApiWithPosition:userLocationStr content:self.topicText imgList:imageUrlArr];
            
            [[YFNetworkingService sharedInstance] sendRequest:postTopicApi callback:^(BOOL success, id result, NSError *error) {
                if (success) {
                    if (completedBlock) {
                        completedBlock(YES);
                    }
                }else{
                    if (completedBlock) {
                        completedBlock(NO);
                    }
                }
            }];
        }else if (_type == PostTopicTypeFeedBack){
            
            // 练系方式
            NSString *connectText = [((YFTopicSynShareCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]]) phoneNumber];
            
            YFLoginApi *feedbackApi = [YFLoginApi userFeedbackWithText:self.topicText images:imageUrlArr emial:connectText];
            [[YFNetworkingService sharedInstance] sendRequest:feedbackApi callback:^(BOOL success, id result, NSError *error) {
                if (success) {
                    if (completedBlock) {
                        completedBlock(YES);
                    }
                }else{
                    if (completedBlock) {
                        completedBlock(NO);
                    }
                }
            }];
        }
    }];
}

- (void)showFeedbackFailAlert:(NSString *)message {
    //用户反馈
    [YFAlertHelper showAlertController:self Title:message message:nil cancelTitle:@"OK" defalutTitle:nil cancelAction:^(UIAlertAction *action) {
        
    } defalutAction:nil];
}

// 上传照片到七牛
- (void)uploadImagesQNComplated:(void(^)(NSArray *imageUrlArr,NSError *error))completedBlock {
    
    __weak typeof(self) weakSelf = self;
    
    if (self.seletePhotoManager.selectedPhotos.count <= 0) {
        if (completedBlock) {
            completedBlock(@[],nil);
        }
        return;
    }
    // 获取照片
    NSArray *images = self.seletePhotoManager.selectedPhotos;
    
    [[YFNetworkingService sharedInstance] sendRequest:[YFMomentApi requestApiWithType:kGetQiNiuUploadImageToMomentApi andParam:nil] callback:^(BOOL success, id result, NSError *error) {
        if (success == NO) {
            if (completedBlock) {
                completedBlock(nil,[NSError errorWithDomain:@"获取七牛token失败" code:-1001 userInfo:nil]);
            }
            return;
        }else {
            // 华南
            NSString *token = [[result responseInfo] objectForKey:@"token"];
            QNUploadOption *option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
                YFLog(@"------>%f",percent);
            }];
            
            // 2.获取Token 成功后上传图片到七牛
            [weakSelf upladToQNImages:images atIndex:0 token:token keys:[NSMutableArray array] filenamesArr:[NSMutableArray arrayWithCapacity:images.count] option:option completed:^(BOOL success, NSMutableArray *fileNameArr) {
                if (success) {
                    NSMutableArray *arrM = [NSMutableArray array];
                    [fileNameArr enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [arrM addObject:[NSString stringWithFormat:@"%@%@",kImageBaseUrl,obj]];
                    }];
                    weakSelf.uploadedImagesArr = arrM.copy;
                    if (completedBlock) {
                        completedBlock(arrM.copy,nil);
                    }
                }else {
                    if (completedBlock) {
                        completedBlock(nil,[NSError errorWithDomain:NSLocalizedString(@"Upload picture failed", @"上传图片失败") code:-1002 userInfo:nil]);
                    }
                }
            }];
        }
    }];
}

/**
 批量上传图片至七牛服务器
 @param         images          图片数组(Asset 对象数组)
 @param         index           开始下标：传0即可
 @param         token           七牛token，服务器请求回来的
 @param         uploadManager   七牛manager
 @param         option          七牛option
 @param         keys            创建一个可变NSMutableArray空数组传进来
 */
- (void)upladToQNImages:(NSArray <UIImage *>*)images
                atIndex:(NSInteger)index
                  token:(NSString *)token
                   keys:(NSMutableArray *)keys
           filenamesArr:(NSMutableArray *)filenamesArr
                 option:(QNUploadOption *)option
              completed:(void(^)(BOOL success,NSMutableArray *fileNameArr))completedBlock {
    if (images.count <= 0) {
        if (completedBlock) {
            completedBlock(NO,nil);
        }
        return;
    }
    
    UIImage *image = images[index];
    __block NSInteger imageIndex = index;
    
    [self.seletePhotoManager getPhotoDataWithAsset:self.seletePhotoManager.selectedAssets[index] completion:^(NSData *data, TZAssetModelMediaType type) {
        
        //    NSData *data = UIImagePNGRepresentation([image wcTimelineCompress]);
        NSTimeInterval time= [[NSDate date] timeIntervalSince1970];
        
        //拼接图片上传后的路径： http://staticapp.coollang.com/bq/social/topicImage + 下划线 + uuid + 下划线 + 时间戳 + 下划线 + 序号 + 中划线 + 图片宽*图片高 + .jpg
        NSString *filename = @"";
        if (type == TZAssetModelMediaTypePhotoGif) {
            filename = [NSString stringWithFormat:@"bq/social/topicImage_%@_%.f_%ld-%d*%d.%@",[User getLastUser].userID,time,(long)imageIndex,(int)image.size.width,(int)image.size.height,@"gif"];
        }else {
            filename = [NSString stringWithFormat:@"bq/social/topicImage_%@_%.f_%ld-%d*%d.%@",[User getLastUser].userID,time,(long)imageIndex,(int)image.size.width,(int)image.size.height,@"jpg"];
        }
        
        [filenamesArr addObject:filename];
        
        
        [[YFNetworkingService qNUploadManager] putData:data key:filename token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
            if (info.isOK) {
                [keys addObject:key];
                YFLog(@"idInex %ld,OK",(long)index);
                if (imageIndex >= images.count - 1) {
                    YFLog(@"上传完成,%@",filename);
                    for (NSString *imgKey in keys) {
                        NSLog(@"%@",imgKey);
                    }
                    if (completedBlock) {
                        completedBlock(YES,filenamesArr);
                    }
                    return ;
                }
                [self upladToQNImages:images atIndex:(imageIndex + 1) token:token keys:keys filenamesArr:filenamesArr option:option completed:completedBlock];
            }else{
                if (completedBlock) {
                    completedBlock(NO,nil);
                }
                YFLog(@"上传失败,%@",filename);
            }
        } option:option];

    }];
    
}

#pragma mark - Action
- (void)backAction:(UIBarButtonItem *)sender {
    [self.view endEditing:YES];
    if (self.sendItem.enabled) {
        [YFAlertHelper showAlertController:self Title:nil message:NSLocalizedString(@"Exit edit?", @"退出此次编辑?") cancelTitle:NSLocalizedString(@"Cancel", @"取消") defalutTitle:NSLocalizedString(@"Confirm", @"确定") cancelAction:^(UIAlertAction *action) {
            
        } defalutAction:^(UIAlertAction *action) {
            [self dismissViewControllerAnimated:YES completion:nil];
        }];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)postTopicAction:(UIBarButtonItem *)sender {
    
    if (_type == PostTopicTypeFeedBack) {
        if (!self.topicText || [self.topicText isEqualToString:@""]) {
            [self showFeedbackFailAlert:@"Feedback content can not be empty"];
            return;
        }
        NSString *connectText = [((YFTopicSynShareCell *)[_collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:2]]) phoneNumber];
        if (connectText.length == 0) {
            [self showFeedbackFailAlert:@"Please enter an email address!"];
            return;
        }else if ([YFLoginHelper checkEmail:connectText] == NO){
            [self showFeedbackFailAlert:@"Enter the e-mail address is not a correct!"];
            return;
        }
    }
    
    if ([self.seletePhotoManager isExistVideo]) {
        
        [YFAlertHelper showAlertController:self Title:NSLocalizedString(@"Not support the video release", @"暂不支持发布视频") message:nil cancelTitle:NSLocalizedString(@"Confirm", @"确定") defalutTitle:nil cancelAction:^(UIAlertAction *action) {
            
        } defalutAction:nil];
        return;
    }
    
    if (self.topicText.length > 1000) {
        
        [YFAlertHelper showAlertController:self Title:[NSString stringWithFormat:NSLocalizedString(@"Have exceeded %d words", @"字数超过1000字"),1000] message:nil cancelTitle:NSLocalizedString(@"Confirm", @"确定") defalutTitle:nil cancelAction:^(UIAlertAction *action) {
            
        } defalutAction:nil];
        return;
    }
   
    [self.view endEditing:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self postTopicCompleted:^(BOOL success) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success) {
            [YFUserDefaults saveMomentRefreshState:YES];
            [self dismissViewControllerAnimated:YES completion:^{
                //[[YFShareManager shareManager] sharePlatformType:self.shareType text:self.topicText images:self.uploadedImagesArr];
            }];
        }else {
            
            [YFAlertHelper showAlertController:self Title:NSLocalizedString(@"Failed to send", @"发送失败") message:nil cancelTitle:NSLocalizedString(@"Confirm", @"确定") defalutTitle:nil cancelAction:^(UIAlertAction *action) {
                
            } defalutAction:nil];
        }
    }];
}

#pragma mark - YFMoveCollectionDelegate
- (void)dragCellCollectionView:(YFMoveCollection *)collectionView newDataArrayAfterMove:(NSArray *)newDataArray {
    
    self.photoModelList = self.dataSourceArr[1];
}

- (NSArray *)dataSourceArrayOfCollectionView:(YFMoveCollection *)collectionView {
    return self.dataSourceArr;
}

#pragma mark -  UICollectionViewDelegate,UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.dataSourceArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.dataSourceArr[section] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewCell *cell = nil;
    YFTopicModel *model = self.dataSourceArr[indexPath.section][indexPath.row];
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0) {
        YFTopicTextviewCell *textCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([YFTopicTextviewCell class]) forIndexPath:indexPath];
        cell = textCell;
        textCell.model = model;
        textCell.type = _type;
        textCell.textViewValueChangeBlock = ^(NSString *text) {
            self.topicText = text;
            NSLog(@"%@",self.topicText);
            [weakSelf UpdateSendItemState];
        };
    }else if (indexPath.section == 1){
        YFTopicPhotoCell *photoCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([YFTopicPhotoCell class]) forIndexPath:indexPath];
        cell = photoCell;
        [photoCell configerMoveViewCellWithItem:model];
    }else {
        YFTopicSynShareCell *shareCell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([YFTopicSynShareCell class]) forIndexPath:indexPath];
        cell = shareCell;
        shareCell.model = model;
        shareCell.type = _type;
        shareCell.SynButtonClickBlock = ^(SSDKPlatformType type) {
            weakSelf.shareType = type;
        };
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    // 退出键盘
    [self.view endEditing:YES];
    
    YFTopicModel *model = self.dataSourceArr[indexPath.section][indexPath.row];
    __weak typeof(self) weakSelf = self;
    if (indexPath.section == 1 ) {
        if (model.type == kYFTopicModelMediaTypeAddPhoto) {
            // 添加照片
            [PhotoActionSheetViewController showInParentViewController:self animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
                [self.seletePhotoManager showPickerControllerWithType:btnType targetVc:self];
            }].isTapCoverViewDismiss = YES;
        }else {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction *originalAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Preview",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                // preview photos or video / 预览照片或者视频
                [weakSelf.seletePhotoManager priviewSeletePhoto:indexPath.row showParentVc:self];
            }];
            
            UIAlertAction *deleteAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Delete",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self deleteSeleteImageAtIndex:indexPath];
            }];
            
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel",nil) style:UIAlertActionStyleCancel handler:nil];
            
            [alertController addAction:originalAction];
            [alertController addAction:deleteAction];
            [alertController addAction:cancelAction];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }
}

- (void)deleteSeleteImageAtIndex:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1) {
        [self.seletePhotoManager.selectedPhotos removeObjectAtIndex:indexPath.row];
        [self.seletePhotoManager.selectedAssets removeObjectAtIndex:indexPath.row];
    }
    [self updatePhotoModelList];
    [self UpdateSendItemState];
    [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:1]];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionReusableView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"MoveCollectFooter" forIndexPath:indexPath];
    // footerView.backgroundColor = [UIColor colorWithHex:0xf5f6fd];
//    footerView.backgroundColor = [UIColor clearColor];
    footerView.backgroundColor = kSeparationLineColor;
    return footerView;
}

/*设置Flowlayout*/
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth, kAutoHei(120));
    }else if (indexPath.section == 1){
        CGFloat itemWH = (kScreenWidth - self.flowLayout.minimumLineSpacing * (kPhotoCol - 1) - self.flowLayout.sectionInset.left - self.flowLayout.sectionInset.right) / 3;
        itemWH = itemWH <= kAutoWid(78) ? itemWH:kAutoWid(78);
        return CGSizeMake(itemWH, itemWH);
    }else {
        return CGSizeMake(kScreenWidth, kAutoHei(94));
    }
    return CGSizeZero;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    if (section == 1) {
        return kPhotoSpace;
    }
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    if (section == 1) {
        return kPhotoSpace;
    }
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    if (section == 1) {
        return UIEdgeInsetsMake(0, kPhotoLeftMargin, 14, kPhotoLeftMargin);
    }
    return UIEdgeInsetsZero;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    CGFloat footerH = kFooterMaxH;
    
    if (section == 2) {
        if (self.photoModelList.count <= 4) {
            _bgImageScale = (footerH + kAutoHei(78)) / collectionView.bounds.size.height;
            _collectionViewBgView.image = [self changeColectionViewBackgroundImageWithScale:_bgImageScale];
            return CGSizeMake(kScreenWidth,footerH);
        }else {
            _bgImageScale = (footerH - kPhotoSpace) / collectionView.bounds.size.height;
            _collectionViewBgView.image = [self changeColectionViewBackgroundImageWithScale:_bgImageScale];
            return CGSizeMake(kScreenWidth,(footerH - kAutoHei(78) - kPhotoSpace));
        }
    }
    return CGSizeZero;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
    CGFloat scaleOffSet = scrollView.contentOffset.y / scrollView.bounds.size.height;
    CGFloat scale = (_bgImageScale + scaleOffSet);
    if (scale < 0) {
        scale = 0;
    }else if(scale > 1){
        scale = 1;
    }
    _collectionViewBgView.image = [self changeColectionViewBackgroundImageWithScale:scale];
}

#pragma mark - Setter & Getter
- (NSMutableArray *)dataSourceArr {
    return [NSMutableArray arrayWithObjects:@[self.textModel],[self photoModelList],@[self.shareModel], nil];
}

- (NSMutableArray *)photoModelList {
    if (_photoModelList == nil) {
        _photoModelList = [NSMutableArray array];
        [self updatePhotoModelList];
    }
    return _photoModelList;
}

- (UICollectionViewFlowLayout *)flowLayout {
    if (!_flowLayout) {
        _flowLayout = [[UICollectionViewFlowLayout alloc] init];
    }
    return _flowLayout;
}

- (YFTopicModel *)addModel {
    if (_addModel == nil) {
        _addModel = [[YFTopicModel alloc] initWithType:kYFTopicModelMediaTypeAddPhoto];
    }
    return _addModel;
}

- (YFTopicModel *)textModel {
    if (_textModel == nil) {
        _textModel = [[YFTopicModel alloc] initWithType:kYFTopicModelMediaTypeText];
    }
    return _textModel;
}

- (YFTopicModel *)shareModel {
    if (_shareModel == nil) {
        _shareModel = [[YFTopicModel alloc] initWithType:kYFTopicModelMediaTypeSynShare];
    }
    return _shareModel;
}

- (YFSeletePhotoManager *)seletePhotoManager {
    if (_seletePhotoManager == nil) {
        _seletePhotoManager = [[YFSeletePhotoManager alloc] init];
    }
    return _seletePhotoManager;
}


@end

